package com.example.vueblog.security;

import cn.hutool.json.JSONUtil;
import com.example.vueblog.common.Result;
import com.example.vueblog.common.enums.ResultEnum;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 无权访问
 * @author yushunshun
 * @date 2022/5/28 22:29
 */

@Component
public class AjaxAccessDeniedHandler implements AccessDeniedHandler{
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
        Result<Object> result = Result.error(ResultEnum.USER_NO_ACCESS.getCode(), ResultEnum.USER_NO_ACCESS.getMessage(), null);

        httpServletResponse.setCharacterEncoding("utf-8");
        httpServletResponse.setContentType("application/json; charset=utf-8");

        PrintWriter writer = httpServletResponse.getWriter();
        writer.write(JSONUtil.toJsonStr(result));
    }
}
